<?php
namespace app\api\controller\com;
use app\api\base\RestfulBase;
class Upload extends RestfulBase
{
    protected $_open_auth = ['user' => false, 'open_api' => false];
    /**
     * @return Response
     */
    protected $config = [
        'file_ext' => ['image' => 'jpeg,png,jpg,gif', 'atta' => 'jpeg,png,jpg,gif,doc,docx,xls,xlsx,zip,pdf,rar'],//附件允许上传的文件类型
        'file_size' => '123213241414',
        'file_rule' => ['date', 'md5', 'sha1']
    ];
    protected $option = [
        'upload_path' => 'apiUploads',
        'upload_level' => ['attachment', 'attachment_safe'], //上传级别
        'upload_type' => ['avatar', 'common_image', 'privacy_image', 'common_attr', 'privacy_attr'],//上传类型
    ];
//    /**
//     * 用户头像上传接口
//     */
//    public function avatar()
//    {
//        $info = $this->_upload(request()->file(), 'attachment', 'avatar', 'date', $this->config['file_ext']['image']);
//        return $info;
//    }
    /**
     * 公共图片上传
     */
    public function common_image()
    {
        $info = $this->_upload(request()->file(), 'attachment', 'common_image', 'date', $this->config['file_ext']['image']);
        return $info;
    }
    /**
     * 隐私图片上传
     */
    public function privacy_image()
    {
        $info = $this->_upload(request()->file(), 'attachment_safe', 'privacy_image', 'date', $this->config['file_ext']['image']);
        return $info;
    }

    public function privacy_image_base64(){
        $image64 = $this->getParams('image64','','trim,strip_tags');
        //$image64 ='';
        $info =  $this->_upload_base64($image64,'attachment_safe','privacy_image',$this->config['file_ext']['image']);
        return $info;
    }

    /**
     * 公共附件上传
     */
    public function common_attr()
    {
        $info = $this->_upload(request()->file(), 'attachment', 'common_attr', 'date', $this->config['file_ext']['atta']);
        return $info;
    }
    /**
     * 隐私附件上传
     */
    public function privacy_attr()
    {
        $info = $this->_upload(request()->file(), 'attachment_safe', 'privacy_attr', 'date', $this->config['file_ext']['atta']);
        return $info;
    }

    /**
     * 附件上传(base64)
     * @param  array $files 上传
     * @param  string $file_level 上传级别
     * @param  string $file_type 上传类型
     * @param  string $file_ext 允许上传类型
     * @return Response
     */
    public function _upload_base64($image64, $file_level, $file_type, $file_ext){

        if (empty($image64)) {
            return $this->apiError('无附件上传');
        }

        if (!in_array($file_level, $this->option['upload_level'])) {
            return $this->apiError('非法级别');
        }

        if (empty($file_type)) {
            return $this->apiError('上传类型不能为空');
        } else {
            if (!in_array($file_type, $this->option['upload_type'])) {
                return $this->apiError('非法类型');
            }
        }

        if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $image64, $result)){
            $image_ext = $result[2];

            if(!in_array($image_ext, explode(',',$file_ext))){
                return $this->apiError('非法文件格式！');
            }

            //图片存储路径 头像路径遵循一定规律
            if (!empty($this->_account['supplier_user_id'])){
                $file_level_child = '/su'.$this->_account['supplier_user_id'];
            }else{
                $file_level_child = '/apply';
            }

            //存储路径
            $image_path = $this->option['upload_path'].'/'.$file_level.$file_level_child.'/'.date('Ymd');

            //图片名称
            if ($image_ext == 'jpeg'){
                $image_name = md5(microtime(true)).'.jpg';
            }else{
                $image_name = md5(microtime(true)).'.'.$image_ext;
            }

            if (!file_exists($image_path)){
                mkdir($image_path,0777,true);
            }

            //服务器文件存储路径
            if (file_put_contents($image_path.'/'.$image_name, base64_decode(str_replace($result[1], '', $image64)))){
                return  $this->apiSuccess('/'.$image_path.'/'.$image_name);
            }else{
                return $this->apiError('图片保存失败!');
            }
        }else{
            return $this->apiError('无法匹配!检查参数');
        }
    }

    /**
     * 附件上传
     * @param  array $files 上传
     * @param  string $file_level 上传级别
     * @param  string $file_type 上传类型
     * @param  string $file_rule 上传规则
     * @param  string $file_ext 允许上传类型
     * @return Response
     */
    protected function _upload($files, $file_level, $file_type, $file_rule, $file_ext)
    {


        if (empty($files)) {
            return $this->apiError('无附件上传');
        }

        if (!in_array($file_level, $this->option['upload_level'])) {
            return $this->apiError('非法级别');
        }

        if (empty($file_type)) {
            return $this->apiError('上传类型不能为空');
        } else {
            if (!in_array($file_type, $this->option['upload_type'])) {
                return $this->apiError('非法类型');
            }
        }

        if (!in_array($file_rule, $this->config['file_rule'])) {
            return $this->apiError('非法规则');
        }

        //图片存储路径 头像路径遵循一定规律
        if (!empty($this->_account['supplier_user_id'])){
            $file_level_child = '/su'.$this->_account['supplier_user_id'];
        }else{
            $file_level_child = '/apply';
        }
        $move_path =  $this->option['upload_path'].'/'.$file_level.$file_level_child;
        //图片命名  头像命名遵循一定规律
        $move_name =  true;

        //创建
        $send = [];
        $res=false;

        foreach ($files as $key => $file) {
//            dump($file);exit;
//            $exif = exif_read_data($_FILES['image_upload']['tmp_name']);

            //类型判断 进行不同的移入操作 图片操作
            if (!$file->check(['size' => $this->config['file_size'], 'ext' => $file_ext])) { //上传前检测
                return $this->apiError($file->getError());
            }
                $info = $file
                    ->validate(['size' => $this->config['file_size'], 'ext' => $file_ext])//验证规则
                    ->rule($file_rule)//生成规则
                    ->move($move_path, $move_name);//移入
                if ($info) {
                    //IOS上传图片修正 开启php_exif扩展
                    $image = \think\Image::open($move_path . '/' . str_replace('\\', '/', $info->getSaveName()));
                    $exif = exif_read_data($move_path . '/' . str_replace('\\', '/', $info->getSaveName()));
                    if(!empty($exif['Orientation'])) {
                        switch($exif['Orientation']) {
                            case 8:
                                $image->rotate(-90)->save($move_path . '/' . str_replace('\\', '/', $info->getSaveName()));
                                break;
                            case 3:
                                $image->rotate(-180)->save($move_path . '/' . str_replace('\\', '/', $info->getSaveName()));
                                break;
                            case 6:
                                $image->rotate(90)->save($move_path . '/' . str_replace('\\', '/', $info->getSaveName()));
                                break;
                        }
                    }

                    // 成功上传后  获取上传信息
                    $data['name'] = $info->getInfo()['name'];//文件原名
                    $data['title'] = $info->getFilename(); //文件名
                    $data['file'] = $move_path . '/' . str_replace('\\', '/', $info->getSaveName()); //文件存储路径
                    $data['ext'] = $info->getExtension(); //扩展名
                    $data['mime'] = $info->getType();//Mine类型
                    $data['size'] = $info->getSize();//尺寸
                    $data['md5'] = $info->hash('md5');//MD5
                    $data['sha1'] = $info->hash('sha1');//SHA1
                    $data['user_id'] = $this->_account['supper_user_id'];
                    $data['upload_time'] = time();//上传时间
                    $data['upload_ip'] = request()->ip();//上传IP

                        $send['files'] = '/'.$data['file'];
                        $send['filed'] = $key;
                        $send['name'] = $data['name'];

                        return $this->apiSuccess($send);

                } else {
                    // 上传失败获取错误信息
                    return $this->apiError($file->getError());
                }

        }

    }
}